package modules.majiang.viewManager
{
	/**
	 *
	 * @author xumin.xu 2013-1-24
	 */

	import com.feng.components.FHSlider;
	import com.feng.components.FSlider;
	import com.netease.protobuf.UInt64;
	
	import flash.display.MovieClip;
	import flash.events.Event;
	import flash.events.MouseEvent;
	import flash.text.TextField;
	
	import communication.majiang.MajiangMsgEvent;
	
	import modules.GameEvent;
	import modules.ViewManager;
	import modules.entity.ActionType;
	import modules.majiang.data.MatchCurrentAction;
	import modules.majiang.data.TableDataModel;
	import modules.majiang.data.TablePlayerDataModel;
	import modules.majiang.data.TablesDataManager;
	
	import utils.FloatHandler;

	public class ActionBetViewManager extends ViewManager
	{
		private var tableId:UInt64;
		
		private var flodButton:MovieClip;

		private var checkButton:MovieClip;

		private var callButton:MovieClip;

		private var betButton:MovieClip;

		private var raiseButton:MovieClip;

		private var raiseShowText:TextField;

		private var _maxRaiseValue:Number = 1000;

		private var _minRaiseValue:Number = 1;

		private var _raiseShowValue:Number = 12;

		private var betHSlider:FSlider;

		public function ActionBetViewManager(tableId:UInt64,mainView:MovieClip)
		{
			super();
			this.tableId = tableId;

			this.mainUI = mainView;

			flodButton = mainView.flodBtn;
			checkButton = mainView.checkBtn;
			callButton = mainView.callBtn;
			betButton = mainView.betBtn;
			raiseButton = mainView.raiseBtn;

			mainView.betBtn_txt.mouseEnabled = false;
			mainView.raiseBtn_txt.mouseEnabled = false;

			mainView.callBtn_txt.mouseEnabled = false;
			mainView.checkBtn_txt.mouseEnabled = false;

			betHSlider = FHSlider.getInstance(mainView.betHSlider);

			raiseShowText = mainView.raise_txt;

			mainView.addEventListener(Event.ADDED_TO_STAGE, onAddToStage);
			mainView.addEventListener(Event.REMOVED_FROM_STAGE, removeFromStage);
		}

		public function get raiseShowValue():Number
		{
			return _raiseShowValue;
		}

		public function set raiseShowValue(value:Number):void
		{
			_raiseShowValue = value;
			raiseShowText.text = FloatHandler.TwoFormatToString(value);
		}

		public function get maxRaiseValue():Number
		{
			return _maxRaiseValue;
		}

		public function set maxRaiseValue(value:Number):void
		{
			_maxRaiseValue = value;
			betHSlider.maximum = value;
		}

		public function get minRaiseValue():Number
		{
			return _minRaiseValue;
		}

		public function set minRaiseValue(value:Number):void
		{
			_minRaiseValue = value;
			betHSlider.minimum = value;
		}

		private function onAddToStage(event:Event):void
		{
			mainUI.addEventListener(MouseEvent.CLICK, onClick);

			betHSlider.addEventListener(Event.CHANGE, changeRaiseValue);
			
			//第一轮的要求押注请求
			dispatcher.addEventListener(MSProto.MSID_NEED_CALL_NTF.toString(), function(event:GameEvent):void
			{
				if(event.data != tableId.toString()) return;
				updateHSilderData();
			});
			
			//要求客户端下注、过牌
			dispatcher.addEventListener(MSProto.MSID_NEED_BET_NTF.toString(), function(event:GameEvent):void
			{
				if(event.data != tableId.toString()) return;
				updateHSilderData();
			});
		}

		private function removeFromStage(event:Event):void
		{

		}

		public function get tableDataModel():TableDataModel
		{
			return TablesDataManager.tableDataModeDic[tableId.toString()];
		}

		/**
		 * 当前游戏动作
		 **/
		private function get matchCurrentAction():MatchCurrentAction
		{
			return tableDataModel.matchCurrentAction;
		}

		private function changeRaiseValue(event:Event):void
		{
			raiseShowValue = betHSlider.value;
		}

		private function onClick(event:MouseEvent):void
		{
			switch (event.target)
			{
				case flodButton:
					//弹出提示框 让玩家判断是否弃牌
//					var data:Object = {};
//					data.infoText = ResourceManager.getInstance().getString('MahjongResource', 'foldMessage');
//					data.clickYesFunction = function():void
//					{
					dispatcher.dispatchEvent(new MajiangMsgEvent(MSProto.MSID_FOLD_REQ.toString(), {tableId: tableId}));
//					};
//					dispatcher.dispatchEvent(new GameEvent(GameEvent.SHOW_INFORMATION, data));
					break;
				case checkButton:
					dispatcher.dispatchEvent(new MajiangMsgEvent(MSProto.MSID_PASS_REQ.toString(), {tableId: tableId}));
					break;
				case callButton:
					dispatcher.dispatchEvent(new MajiangMsgEvent(MSProto.MSID_CALL_REQ.toString(), {tableId: tableId}));
					break;
				case betButton:
					onClickActionHandler(ActionType.BET);
					break;
				case raiseButton:
					onClickActionHandler(ActionType.RAISE);
					break;
				case mainUI.min_btn:
					allInClick('min');
					break;
				case mainUI.pot1_btn:
					allInClick('0.25');
					break;
				case mainUI.pot2_btn:
					allInClick('0.5');
					break;
				case mainUI.pot3_btn:
					allInClick('1');
					break;
				case mainUI.all_btn:
					allInClick('allin');
					break;
			}
		}

		/**
		 * 更新滑动条的最大最小数据
		 **/
		private function updateHSilderData():void
		{
			//计算本轮下注 当前下注最高值
			var maxBet:Number = 0;
			for each (var betInfo:Object in tableDataModel.epicycleBetInfos)
			{
				maxBet = Math.max(betInfo.currentBet, maxBet);
			}

			//需要下注的最小金额
			var needMinBet:Number = tableDataModel.tableDataFromLobby.maxBlinds;
			//如果前面有人下注，值为 当前下注最高值 的两倍
			if (maxBet > 0)
			{
				needMinBet = maxBet * 2;
			}
			//我当前下注金额
			var myBetInfo:Object = tableDataModel.epicycleBetInfos[tableDataModel.sitChairId];
			var myTotalBet:Number = 0;
			if (myBetInfo != null)
			{
				myTotalBet = myBetInfo.currentBet;
			}
			//我能加注到的最大金额
			var myCanBetMax:Number = tableDataModel.money + myTotalBet;

			//玩家加注到的最大金额列表
			var canBetMaxList:Array = [];
			for (var i:int = 1; i <= 6; i++)
			{
				var tablePlayerDataModel:TablePlayerDataModel = tableDataModel.seatedPlayers[i];
				if (tablePlayerDataModel != null)
				{
					var isInMatch:Boolean = tableDataModel.isInMatch(i);

					//判断玩家是否还在玩
					if (isInMatch)
					{
						var totalBet:Number = 0;
						betInfo = tableDataModel.epicycleBetInfos[i];
						if (betInfo && betInfo.currentBet)
						{
							totalBet = betInfo.currentBet;
						}
						//已下注金额+剩余金额
						var canBetMax:Number = totalBet + tablePlayerDataModel.money;
						if (!canBetMax)
						{
							trace(canBetMax);
						}
						canBetMaxList.push(canBetMax);
					}
				}
			}
			//从小到大排序
			canBetMaxList.sort(function(a:Number, b:Number):int
			{
				if (a > b)
					return 1;
				if (a < b)
					return -1;
				return 0;
			});

			//取第二大的值
			var secondMax:Number = myCanBetMax;
			if (canBetMaxList.length > 1)
			{
				secondMax = canBetMaxList[canBetMaxList.length - 2];
			}

			needMinBet = FloatHandler.TwoFormat(needMinBet);
			myCanBetMax = FloatHandler.TwoFormat(myCanBetMax);
			secondMax = FloatHandler.TwoFormat(secondMax);
			maxBet = FloatHandler.TwoFormat(maxBet);

			//计算最小加注值
			minRaiseValue = Math.min(needMinBet, myCanBetMax, secondMax);
			//计算最大加注值
			maxRaiseValue = Math.min(secondMax, myCanBetMax);

			if (minRaiseValue == maxRaiseValue && maxRaiseValue <= maxBet)
			{
				betButton.enabled = false;
				raiseButton.enabled = false;

				betHSlider.enabled = false;
			}
			else
			{
				betButton.enabled = true;
				raiseButton.enabled = true;
				betHSlider.enabled = true;
			}

			//刷新显示滚动条的值（默认最小值）
			betHSlider.value = betHSlider.minimum;

			if (FloatHandler.TwoFormat(raiseShowValue) == 0)
			{
				trace("计算出错了。。。。。");
				logger("计算出错了。。。。。");
			}
		}

		/**
		 * 选择操作
		 **/
		private function onClickActionHandler(action:String):void
		{
			var raiseValue:Number = parseFloat(raiseShowText.text.replace(",", ""));

			//计算本轮下注 当前下注最高值
			var maxBet:Number = 0;
			for each (var betInfo:Object in tableDataModel.epicycleBetInfos)
			{
				maxBet = Math.max(betInfo.currentBet, maxBet);
			}
			var money:Number = raiseValue - maxBet;

			switch (action)
			{
				//下注（押注）
				case ActionType.BET:
					dispatcher.dispatchEvent(new MajiangMsgEvent(MSProto.MSID_BET_REQ.toString(), {tableId: tableId, money: money}));
					break;
				//加注
				case ActionType.RAISE:
					dispatcher.dispatchEvent(new MajiangMsgEvent(MSProto.MSID_RAISE_REQ.toString(), {tableId: tableId, money: money}));
					break;
			}
			//情况当前动作
			//matchCurrentAction.clear();
		}

		private function allInClick(type:String):void
		{
			switch (type)
			{
				case "allin":
					betHSlider.value = maxRaiseValue;
					break;
				case "min":
					betHSlider.value = minRaiseValue;
					break;
				case "0.25":
				case "0.5":
				case "1":
					var multipleValue:Number = parseFloat(type);

					//计算奖池中的所有钱
					var potAmount:Number = tableDataModel.bonusPotsData.totalMoney;

					var raiseAmount:Number = parseFloat((multipleValue * potAmount).toFixed(2));
					if (raiseAmount < minRaiseValue)
					{
						raiseAmount = minRaiseValue
					}
					else if (raiseAmount > maxRaiseValue)
					{
						raiseAmount = maxRaiseValue;
					}
					betHSlider.value = raiseAmount;
					break;
			}
		}

		public function setBetButtonStatus(betButtonVisible:Boolean, raiseButtonVisible:Boolean, isNeedCall:Boolean):void
		{
			mainUI.betBtn_txt.visible = betButton.visible = betButtonVisible;

			mainUI.raiseBtn_txt.visible = raiseButton.visible = raiseButtonVisible;
			if (betButtonVisible)
			{
				betButton.enabled = true;
			}
			else if (raiseButtonVisible)
			{
				raiseButton.enabled = true;
			}
			else
			{
				mainUI.betBtn_txt.visible = betButton.visible = !isNeedCall;
				betButton.enabled = false;

				mainUI.raiseBtn_txt.visible = raiseButton.visible = isNeedCall;

				raiseButton.enabled = false;
			}
		}

		public function needCall(showCallMoney:Number):void
		{
			checkButton.visible = false;
			mainUI.checkBtn_txt.visible = false;

			callButton.label = FloatHandler.TwoFormatToString(showCallMoney) + "";
			callButton.visible = true;
			mainUI.callBtn_txt.visible = true;

			if (FloatHandler.TwoFormat(matchCurrentAction.callMoney) == 0)
			{
				checkButton.visible = true;
				mainUI.checkBtn_txt.visible = true;

				callButton.visible = false;
				mainUI.callBtn_txt.visible = false;
			}

			setBetButtonStatus(false, true, true);
			mainUI.visible = true;
		}

		public function needBet():void
		{
			checkButton.visible = true;
			mainUI.checkBtn_txt.visible = true;

			callButton.visible = false;
			mainUI.callBtn_txt.visible = false;

			setBetButtonStatus(true, false, false);
			mainUI.visible = true;
		}

	}
}
